//
//  Encryption.m
//  Tospur-text
//
//  Created by Tospur_hewei on 15/9/28.
//  Copyright (c) 2015年 Tospur_hewei. All rights reserved.
//

#import "Encryption.h"
#import <CommonCrypto/CommonCrypto.h>
@implementation Encryption

static Encryption *encrytion;
+ (Encryption *)shareInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        encrytion = [[Encryption alloc]init];
    });
    return encrytion;
}
//MD5加密
- (NSString *) md5: (NSString *) inPutText
{
    const char *cStr = [inPutText UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, strlen(cStr), result);
    
    return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] lowercaseString];
}


//一百以内的随机偶数
int arc4randomNumber()
{
    int number =  arc4random()%100;
    if (number % 2 == 0) {
        return number;
    }
    return arc4randomNumber();
}

//SHA1加密方式
- (NSString*)sha1
{
    //获取系统时间
    NSString* date;
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYYMMddHHmm"];
    date = [formatter stringFromDate:[NSDate date]];
    //一百以内的随机数
    NSInteger number;
    number = arc4randomNumber();
    NSString *AppSer = @"654321cba";
    NSString *signature = [NSString stringWithFormat:@"%@%@%ld",AppSer,date,(long)number];
    //NSLog(@"日期 + 随机数 === %@  +  %ld",date,(long)number);
    //NSString *signature = [self jiami];
    const char  *cstr = [signature cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:signature.length];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, data.length, digest);
    
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    //NSLog(@"加密后 ---->> %@",output);
    return output;
}

@end
